#include "ohos_video_track.h"

namespace ohoswebrtc {

OHOSVideoTrack::OHOSVideoTrack(rtc::scoped_refptr<webrtc::VideoTrackInterface> track, rtc::scoped_refptr<OHOSPeerConnectionFactoryInterface> peer_connection_factory)
    : track_(track),
      worker_thread_(peer_connection_factory->worker_thread()),
      peer_connection_factory_(peer_connection_factory),
      render_lock_(new webrtc::Mutex()) {
  RTC_LOG(LS_INFO) << __FUNCTION__ << ": Ctor";
  id_ = track->id();
  kind_ = track->kind();
}

OHOSVideoTrack::~OHOSVideoTrack() {
  RTC_LOG(LS_INFO) << __FUNCTION__ << ": Dtor";
}

void OHOSVideoTrack::AddRenderer(OHOSVideoRenderInterface* renderer) {
  if (worker_thread_ != nullptr && !worker_thread_->IsCurrent()) {
      worker_thread_->BlockingCall([&, this]() { this->AddRenderer(renderer); });
      return;
  }
  
  webrtc::MutexLock cs(render_lock_.get());
  for (auto it = renderers_.begin(); it != renderers_.end(); ) {
    if ((*it)->get_render().get() == renderer) { 
      RTC_LOG(LS_INFO) << "renderer is already attached to this track";
      return;
    } else {
      ++it;
    }
  }
  
  rtc::scoped_refptr<OHOSVideoRenderInterface> ohos_renderer(renderer);
  rtc::scoped_refptr<OHOSVideoRenderAdapter> render_adapter = rtc::scoped_refptr<OHOSVideoRenderAdapter>(
            new rtc::RefCountedObject<OHOSVideoRenderAdapter>(ohos_renderer));

  renderers_.push_back(render_adapter);
  track_->AddOrUpdateSink(render_adapter.get(), rtc::VideoSinkWants());
}

void OHOSVideoTrack::RemoveRenderer(OHOSVideoRenderInterface* renderer) {
  if (worker_thread_ != nullptr && !worker_thread_->IsCurrent()) {
      worker_thread_->BlockingCall([&, this]() { this->RemoveRenderer(renderer); });
      return;
  }
  
  webrtc::MutexLock cs(render_lock_.get());
  for (auto it = renderers_.begin(); it != renderers_.end(); ) {
    if ((*it)->get_render().get() == renderer) { 
      it = renderers_.erase(it);
      track_->RemoveSink((*it).get());
      break; 
    } else {
      ++it;
    }
  }
}

rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> OHOSVideoTrack::track() {
  return track_;
}

rtc::scoped_refptr<webrtc::VideoTrackInterface> OHOSVideoTrack::video_track() {
  return track_;
}

}
